<?php
class ManageCommentsController extends Controller {
	private $_model;
	public $layout='//layouts/main';
	public $pageTitle="Manage comments";

	public function init()
	{
		Yii::app()->theme = 'backend';
		parent::init();
	}

	public function actionAdmin()
	{
		if (isset($_POST['comments-grid_c0'])) {
			foreach ($_POST['comments-grid_c0'] as $ID)
			{
				$model = $this->loadModelByID($ID);

				// Xoa khoi db
				if ($model->delete() == 'ALL')
				{
					
				}
			}
		}
		$model = new Comment('search');
		$model->unsetAttributes();
		if (isset($_GET['Comment'])) {
			$model->setAttributes($_GET['Comment']);
		}
		$this->render('admin', array(
			'model' => $model,
		));		
	}
	
	public function actionArticleComments($article_id = null)
	{
		if (isset($_POST['comments-grid_c0'])) {
			foreach ($_POST['comments-grid_c0'] as $ID)
			{
				$model = $this->loadModelByID($ID);

				// Xoa khoi db
				if ($model->delete() == 'ALL')
				{
					
				}
			}
		}
		
		$model = new Comment('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Comment']))
			$model->attributes = $_GET['Comment'];
		$model->article_id = $article_id;
		
		$articlename = $article_id;
		if ($articleModel=Article::Model()->findByAttributes(array('id'=>$article_id))) {
			$articlename = $articleModel->title;
		}
		
		$this->pageTitle .= ' for article "'. Comment::model()->limit_text($articlename, 10) .'"'; 
		$this->render('list', array(
			'model' => $model,
		));
	}
	
	public function actionView($id) {
		$this->pageTitle = 'View an comment';
		$this->render('view', array(
			'model' => $this->loadModel($id, 'Comment'),
		));
	}
	
	public function actionCreate($article_id = null) {
        $model = new Comment;
		
		if (isset($_POST['Comment'])) {
			$model->setAttributes($_POST['Comment']);
			$model->article_id	=	$article_id;
			$model->user_id 	= 	Yii::app()->user->id;
			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		} else {
			$model->status = 1;
		}

		$this->pageTitle = 'Write an comment';
		$this->render('create', array(
			'model' => $model,
		));
	}
	
	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'Comment');
		
		if (isset($_POST['Comment'])) {
			$model->setAttributes($_POST['Comment']);
			
			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->pageTitle = 'Update an comment';
		$this->render('update', array(
			'model' => $model,
		));
	}
	
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Comment::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
}
?>